package com.neusoft.elmboot.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;

import java.util.Map;

public class AlipayUtil {
    // 沙箱环境网关地址
//    private static final String ALIPAY_GATEWAY = "https://openapi.alipaydev.com/gateway.do";

//    private static final String ALIPAY_GATEWAY = "https://openapi.alipay.com/gateway.do";
    // 新版沙箱环境的网关地址
    private static final String ALIPAY_GATEWAY = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 商户应用ID （我的沙箱应用ID）
    public static final String APP_ID = "9021000135613524";
    // 商户私钥 （我的应用私钥）
    public static final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBflXnb5CpDJzQBm/XDRw/MfX5Cog2JEioSpg5QIfs0h0egvihZTt7dKQ6EifbwmWptVvWnBuuODrBxZlX/G1yW5fOWyXbybC8DHt9+09ZYgZvZnLc4vWxU4Yuk5xHLE+j1lpTJW4byELNoDlMCnlXZ1COFyysVee23YxHKfn6LXAdoQ1sC0u0MWC4M1vhtTNZBiEnFkN2KuRzdWRxA2BvY6aBWa3e8Bb9aO1fIO0/5F8xi/HC2prKRqydprfPPszrIAapC2J7jjfKB4IFd+GjLeDW6Oydl4AWqXh1E4HdELzlgJPWlQvs3DiqYdJOLSOY30VGDNilZPqofy8xkgqZAgMBAAECggEANmhuj59AmMbD3GPX+fN4OtUzFEBomtcD8DHnY6bJdaeStI8zCB0QsP6BQiT+ukcjj/qza6iLuNfHWEM9+soE8lepoPqLHZ3QtDJKcNR2soeNTKEvAcAamzcM2eULdJwZmi0mJml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3+Smuti1STxQ==";
    // 支付宝公钥 （我的沙箱支付宝公钥）
    public static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwuLzlo+4pGv2eKGbBtMKXBdzwqY/3rfr5tuNmUIABt4fwJ8zqhhtOF3W0Bu5qoGqNg2U0s4iMbbW1akc/suAkLB3mESju2ldj3Ns2IVC2KiXNi8Zqd4yvq2H/j9om07DY6rJ5xXRglCYgiyl60oNeBC3Ix3sul2pxDUIJA0wIDsMZsOFIe59pg3BXO5w9z+2vlaeHFDUXZiOrBX44cqENTmVvkTtLPkgfZVS2upegkP185WWV/wlz9efaECwerqlLpqkwwyyVSTnhkcX81sTEpGyu/c0WT+GYLAAQ6rbrV5z6XL+36L7XBYqYzlfU0gr1aK8AdzyyHWOIUQ6SHQZ+QIDAQAB";

    // 支付宝同步通知地址
    private static final String RETURN_URL = "http://localhost:8080/payment/returnUrl";
    // 支付宝异步通知地址
    private static final String NOTIFY_URL = "http://egvf6b.natappfree.cc/payment/notifyUrl";


    // 编码格式
    public static final String CHARSET = "UTF-8";

    // 返回格式
    public static final String FORMAT = "json";

    // 签名类型
    public static final String SIGN_TYPE = "RSA2";

    public static AlipayClient getAlipayClient() {
        return new DefaultAlipayClient(ALIPAY_GATEWAY, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
    }

    /**
     * 调用支付宝的支付接口的核心方法
     * @param outTradeNo
     * @param totalAmount
     * @param subject
     * @param productCode - 支付交易的类型（电脑网站、手机网站）
     * @return
     * @throws AlipayApiException
     */
    public static String createPayOrder(String outTradeNo, String totalAmount,
                                        String subject, String productCode) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(subject);
        model.setProductCode(productCode); // "FAST_INSTANT_TRADE_PAY"
        model.setBody("");
        request.setBizModel(model);

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            throw new AlipayApiException("创建支付订单失败");
        }
    }

    public static String createMobilePayOrder(String outTradeNo, String totalAmount,
                                        String subject, String productCode) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(totalAmount);
        model.setSubject(subject);
        model.setProductCode(productCode);
        model.setBody("");
        request.setBizModel(model);

        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody();
        } else {
            throw new AlipayApiException("创建移动端支付订单失败");
        }
    }




    // 验证支付宝回调参数的签名
    public static boolean verify(Map<String, String> params) {
        try {
            // 调用SDK的验签方法进行签名验证
            // 这里的 alipayPublicKey 是你自己的支付宝公钥
            // 这里的 charset 是你使用的字符编码，一般为 UTF-8
            // 这里的 signType 是签名类型，一般为 RSA2
            boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE);

            return signVerified;
        } catch (AlipayApiException e) {
            // 处理异常，打印日志等
            e.printStackTrace();
            return false;
        }
    }
}
